//
//  BCAddNoteViewController.m
//  Memo
//
//  Created by 李雪 on 16/3/9.
//  Copyright © 2016年 www.lanou3g.com 蓝鸥科技. All rights reserved.//

#import "BCAddNoteViewController.h"
#import "NSDate+Calendar.h"
#import "BCDateBase.h"

#define DefaultTextViewContent @"请输入内容..."

@interface BCAddNoteViewController ()
@property (strong,nonatomic) UITableView* mytable;

@property (strong,nonatomic) UILabel* timeLabel;
@property (strong,nonatomic) UILabel* alertModeLabel;
@property (strong,nonatomic) UITextView* textView;

@property (strong,nonatomic) NSString* content;
@property (assign,nonatomic) BCAlertMode alertMode;

@end

@implementation BCAddNoteViewController
@synthesize mytable;
@synthesize content;
@synthesize alertMode;
@synthesize chosenTime;
@synthesize timeLabel;
@synthesize textView;
@synthesize alertModeLabel;

-(void)updateDisplay
{
    NSDateComponents* comp=[[NSDateComponents alloc]init];
    [comp setHour:-8];
    NSCalendar* cal=[[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDate *aDate=[cal dateByAddingComponents:comp toDate:self.chosenTime options:0];
    NSDateFormatter* fm=[[NSDateFormatter alloc]init];
    [fm setCalendar:cal];
    [fm setDateFormat:@"yyyy-MM-dd  HH:mm"];
    NSString *timeStr=[fm stringFromDate:aDate];
    NSLog(@"addVCChosenTime=%@",timeStr);
    timeLabel.text=[NSString stringWithFormat:@"时间%@",timeStr];
    
    NSString* alertModeStr;
    switch (self.alertMode) {
        case BCAlertmodeRing:
            alertModeStr=@"响铃";
            break;
            
        case BCAlertModeShake:
            alertModeStr=@"震动";
            break;
            
        case BCAlertModeSoundOff:
            alertModeStr=@"静音";
            break;
            
        default:
            break;
    }
    self.alertModeLabel.text=[NSString stringWithFormat:@"提醒方式：%@",alertModeStr];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.title=@"日程表";
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
//    if (IOS_VERSION_Above_7_0) {
//        self.edgesForExtendedLayout=UIRectEdgeNone;
//    }
	// Do any additional setup after loading the view.
    self.navigationItem.leftBarButtonItem=[[UIBarButtonItem alloc]initWithTitle:@"确定" style:UIBarButtonItemStylePlain target:self action:@selector(save)];
    self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(goBack)];
    //添加tableView
    self.mytable=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height-44) style:UITableViewStyleGrouped];
    self.mytable.delegate=self;
    self.mytable.dataSource=self;
    self.mytable.allowsSelection=NO;
    [self.view addSubview:self.mytable];
    //显示选中时间的timeLabel
    self.timeLabel=[[UILabel alloc]initWithFrame:CGRectMake(8, 4,260,36)];
    self.timeLabel.backgroundColor=[UIColor clearColor];
    self.timeLabel.userInteractionEnabled=YES;
    self.timeLabel.font=[UIFont systemFontOfSize:16];
    UITapGestureRecognizer* tapGR1=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapOnTimeLabel)];
    [self.timeLabel addGestureRecognizer:tapGR1];
    //备忘输入文本框textView
    self.textView=[[UITextView alloc]initWithFrame:CGRectMake(4, 4, 292, 152)];
    self.textView.delegate=self;
    self.textView.font=[UIFont systemFontOfSize:16];
    self.textView.textColor=[UIColor lightGrayColor];
    self.textView.backgroundColor=[UIColor clearColor];
    //显示提醒模式的alertModeLabel
    self.alertModeLabel=[[UILabel alloc]initWithFrame:CGRectMake(8, 4,260,36)];
    self.alertModeLabel.userInteractionEnabled=YES;
    self.alertModeLabel.backgroundColor=[UIColor clearColor];
    self.alertModeLabel.font=[UIFont systemFontOfSize:16];
    UITapGestureRecognizer* tapGR2=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapOnAlertModeLabel)];
    [self.alertModeLabel addGestureRecognizer:tapGR2];
    //初始化视图
    self.textView.text=DefaultTextViewContent;
    
    NSDate* now=[NSDate date];
    
    if (!self.chosenTime) {
        self.chosenTime=now;
    }
    
    if ([self.chosenTime compare:now]==NSOrderedDescending) {
        self.originChosenTime=now;
    }else{
        self.originChosenTime=self.chosenTime;
    }
    
    NSDateComponents* comp=[[NSDateComponents alloc]init];
    [comp setHour:8];
    NSCalendar* cal=[[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    self.chosenTime=[cal dateByAddingComponents:comp toDate:self.chosenTime options:0];
    NSLog(@"when did load,ChosenTime=%@ ",self.chosenTime);
    self.alertMode=0;
    [self updateDisplay];
}

-(void)viewDidUnload
{
    self.timeLabel=nil;
    self.textView=nil;
    self.alertModeLabel=nil;
    [super viewDidUnload];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark -
#pragma mark Jiont Method
-(void)goBack
{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)save
{
    //保存修改
    if ([self.textView.text isEqualToString:DefaultTextViewContent]||[self.textView.text isEqualToString: @""]) {
        UIAlertView *notifier=[[UIAlertView alloc]initWithTitle:@"提示" message:@"请输入备忘内容" delegate:nil cancelButtonTitle:@"我知道了" otherButtonTitles:nil, nil];
        [notifier show];
    }else{
    //写入数据库
        [[BCDateBase defaultBase] insertANewNoteOnTime:self.chosenTime withCotent:self.textView.text AlertMode:self.alertMode];
        [self.navigationController popViewControllerAnimated:YES];
    }
}

-(void)tapOnTimeLabel
{
    NSLog(@"tap on TimeLabel");
    NSDate* maxTime=[NSDate dateWithYear:2050 Month:12 Day:31 Hour:23 Minute:59];
    
    NSDateComponents* comp=[[NSDateComponents alloc]init];
    [comp setHour:8];
    NSCalendar* cal=[[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDate *aDate=[cal dateByAddingComponents:comp toDate:self.originChosenTime options:0];
    BCDatePickerController* pickerVC=[[BCDatePickerController alloc]initTimeRangeFromDate:aDate ToDate:maxTime WithType:PickerTypeDateAndTime];
    pickerVC.delegate=self;
    [pickerVC setDate:self.chosenTime];
    [self.navigationController pushViewController:pickerVC animated:YES];
}

-(void)tapOnAlertModeLabel
{
    NSLog(@"tap on AlertModeLabel");
    BCAlertModePickerViewController* alertPicker=[[BCAlertModePickerViewController alloc
                                                   ]init];
    alertPicker.delegate=self;
    alertPicker.selectedMode=self.alertMode;
    [self.navigationController pushViewController:alertPicker animated:YES];
}

#pragma mark -
#pragma mark TableView Delegate Method and TableView DataSource Method
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString* CellIdentifier=@"cell";
    UITableViewCell* cell=[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (!cell) {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    if (indexPath.section==0) {
        [cell.contentView addSubview:self.timeLabel];
        cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
    }else if (indexPath.section==1){
        [cell.contentView addSubview:self.textView];
    }else{
        [cell.contentView addSubview:self.alertModeLabel];
        cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==1) {
        return 160.0f;
    }
    return 44.0f;
}
#pragma mark -
#pragma mark textView Delegate Method

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if ([text isEqualToString:@"\n"]) {
        [self.textView resignFirstResponder];
    }
    return YES;
}

- (BOOL)textViewShouldBeginEditing:(UITextView *)aTextView
{
    if ([aTextView.text isEqualToString: DefaultTextViewContent])
    {
        aTextView.text=nil;
        aTextView.textColor=[UIColor blackColor];
    }
    return YES;
}

- (BOOL)textViewShouldEndEditing:(UITextView *)aTextView
{
    if (aTextView.text==nil||[aTextView.text isEqualToString:@""]) {
        aTextView.text=DefaultTextViewContent;
        aTextView.textColor=[UIColor lightGrayColor];
    }
    return YES;
}

#pragma mark -
#pragma mark BCDatePickController Delegate Method
-(void)datePickerController:(BCDatePickerController*) datePickerController   FinishedWithSelectedDate:(NSDate*) selectedDate
{
    self.chosenTime=selectedDate;
    NSLog(@"chosenTime=%@",self.chosenTime);
    [self updateDisplay];
}
#pragma mark -
#pragma mark AlertModerPicker Delegate Method
-(void)alertModePickerViewController:(BCAlertModePickerViewController*) pickerVC  DidSelectedAlertMode:(BCAlertMode) alertModer
{
    self.alertMode=alertModer;
    [self updateDisplay];
}
@end
